package org.microblog.socket;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.*;
import org.json.JSONObject;
import org.json.JSONArray;

@ServerEndpoint("/ws2/{username}")
public class ChatWebSocket2 {
    // 用户名 → Session 映射
    private static final Map<String, Session> userSessions = new ConcurrentHashMap<>();
    private String username;

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        System.out.println(username);
        this.username = username;
        userSessions.put(username, session);
        broadcastOnlineUsers();
    }

    @OnMessage
    public void onMessage(String rawMessage, Session sender) {
        try {
            JSONObject json = new JSONObject(rawMessage);
            String type = json.getString("type"); // "group" or "private"
            String message = json.getString("message");

            if ("group".equals(type)) {
                // 群聊：发送给所有人（包括自己）
                broadcast(message, sender);
            } else if ("private".equals(type)) {
                String toUser = json.getString("to");
                if (userSessions.containsKey(toUser)) {
                    Session targetSession = userSessions.get(toUser);
                    JSONObject response = new JSONObject();
                    response.put("from", username);
                    response.put("type", "private");
                    response.put("message", message);
                    targetSession.getBasicRemote().sendText(response.toString());
                } else {
                    sender.getBasicRemote().sendText("用户 " + toUser + " 不在线");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        userSessions.remove(username);
        broadcastOnlineUsers();
    }

    // 群聊广播（排除自己）
    private void broadcast(String message, Session sender) {
        for (Session session : userSessions.values()) {
            if (!session.equals(sender)) {
                try {
                    JSONObject response = new JSONObject();
                    response.put("from", username);
                    response.put("type", "group");
                    response.put("message", message);
                    session.getBasicRemote().sendText(response.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 广播在线用户列表
    private void broadcastOnlineUsers() {
        JSONObject onlineUsers = new JSONObject();
        onlineUsers.put("type", "online_users");
        onlineUsers.put("users", new JSONArray(userSessions.keySet()));
        for (Session session : userSessions.values()) {
            try {
                session.getBasicRemote().sendText(onlineUsers.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}